package com.example.sendmessage.server;

import com.example.sendmessage.common.*;
import com.example.sendmessage.server.core.BasicProperties;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BrokerServer {
    // 构建服务器连接
    private ServerSocket serverSocket = null;
    // 默认一个虚拟机，待扩展（添加关于虚拟机的类）
    private VirtualHost virtualHost = new VirtualHost("default");
    // 储存所有的客户端，复用同一个tcp连接，key为channelId
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    // 使用线程池来处理客户端的请求
    private ExecutorService executorService = null;
    // 是否继续运行
    private volatile boolean runnable = true;

    // 设置服务器端口号
    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    // 启动服务器
    public void start() throws IOException {
        System.out.println("[BrokerServer] 服务器启动！");
        // 创建线程池，这个没有线程上限
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                // 等待客户端的连接
                Socket clientSocket = serverSocket.accept();
                executorService.submit(() -> {
                    // 处理一个客户的连接
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器关闭！");
        }
    }

    public void stop() throws IOException {
        runnable = false;
        executorService.shutdownNow();
        serverSocket.close();
    }


    private void processConnection(Socket clientSocket) {
        // 客户端请求和响应流
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            // 根据自定义应用程协议解析
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                // while是让客户端连接不断开
                while (true) {
                    // 读取客户端请求
                    Request request = readRequest(dataInputStream);
                    // 解析请求并计算响应
                    Response response = process(request, clientSocket);
                    // 将响应写回客户端
                    writeResponse(dataOutputStream, response);
                }
            }
        } catch (EOFException | SocketException e) {
            System.out.println("[BrokerServer] connection关闭！客户端地址：" + clientSocket.getInetAddress().toString()
            +":端口号：" + clientSocket.getPort());
        } catch (IOException | ClassNotFoundException | MqException e) {
            System.out.println("[BrokerServer] 处理请求时发生错误："+ e.getMessage());
        } finally {
            try {
                // 关闭socket连接
                clientSocket.close();
                // 顺便清理掉该客户端连接的channel
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        // 读取请求类型
        int type = dataInputStream.readInt();
        request.setType(type);
        int length = dataInputStream.readInt();
        request.setLength(length);
        byte[] body = new byte[length];
        int readNum = dataInputStream.read(body);
        if (readNum != length) {
            throw new IOException("[BrokerServer] 读取到的数据长度与预期不一致");
        }
        request.setPayload(body);
        return request;
    }

    // 根据请求计算响应
    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 打印日志，初步了解payload的内容
        BasicArgument basicArgument = (BasicArgument) BinaryTool.fromBytes(request.getPayload());
        System.out.println("[BrokerServer] Request type = " + request.getType() + ",length = " + request.getLength()
                + ",channelId = " + basicArgument.getChannelId() + ",rid = " + basicArgument.getRid());
        // 根据请求类型进行处理
        boolean ok = true;
        if (request.getType() == 0x1) {
            // 表示创建一个channel
            sessions.put(basicArgument.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] 创建channel成功！channelId = " + basicArgument.getChannelId());
        } else if (request.getType() == 0x2) {
            // 表示销毁一个channel
            sessions.remove(basicArgument.getChannelId());
            System.out.println("[BrokerServer] 销毁channel成功！channelId = "+ basicArgument.getChannelId());
        } else if (request.getType() == 0x3) {
            // 表示创建一个交换机
            ExchangeDeclareArgument argument = (ExchangeDeclareArgument)BinaryTool.fromBytes(request.getPayload());
            ok = virtualHost.exchangeDeclare(argument.getExchangeName(), argument.getExchangeType(), argument.isDurable(),
                    argument.isAutoDelete(), argument.getArguments());
        } else if (request.getType() == 0x4) {
            // 表示删除一个交换机
            ExchangeDeleteArgument argument = (ExchangeDeleteArgument)BinaryTool.fromBytes(request.getPayload());
            ok = virtualHost.exchangeDelete(argument.getExchangeName());
        } else if (request.getType() == 0x5) {
            // 表示创建一个队列
            QueueDeclareArgument argument = (QueueDeclareArgument) BinaryTool.fromBytes(request.getPayload());
            ok = virtualHost.queueDeclare(argument.getQueueName(), argument.isDurable(), argument.isExclusive(),
                    argument.isAutoDelete(), argument.getArguments());
        } else if (request.getType() == 0x6) {
            // 表示删除一个队列
            QueueDeleteArgument argument = (QueueDeleteArgument) BinaryTool.fromBytes(request.getPayload());
            ok = virtualHost.queueDelete(argument.getQueueName());
        } else if (request.getType() == 0x7) {
            // 表示创建绑定
            QueueBindArgument argument = (QueueBindArgument) BinaryTool.fromBytes(request.getPayload());
            ok = virtualHost.queueBind(argument.getExchangeName(), argument.getExchangeName(), argument.getBindingKey());
        } else if (request.getType() == 0x8) {
            // 表示解除绑定
            QueueUnbindArgument argument = (QueueUnbindArgument) BinaryTool.fromBytes(request.getPayload());
            ok = virtualHost.queueUnBind(argument.getExchangeName(), argument.getQueueName());
        } else if (request.getType() == 0x9) {
            // 发送消息
            BasicPublishArgument argument = (BasicPublishArgument) BinaryTool.fromBytes(request.getPayload());
            ok = virtualHost.basicPublish(argument.getExchangeName(), argument.getRoutingKey(),
                    argument.getBasicProperties(), argument.getBody());
        } else if (request.getType() == 0xa) {
            // 订阅消息
            BasicConsumeArgument argument = (BasicConsumeArgument) BinaryTool.fromBytes(request.getPayload());
            ok = virtualHost.basicConsume(argument.getConsumerTag(), argument.getQueueName(), argument.isAutoAck(),
                    new Consumer() {
                        @Override
                        public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                            // 服务器的回调就是将消息发送给客户端
                            Socket clientSocket = sessions.get(consumerTag);
                            if (clientSocket == null || clientSocket.isClosed()) {
                                throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭！");
                            }
                            // 构造响应数据
                            SubscribeReturn subscribeReturn = new SubscribeReturn();
                            subscribeReturn.setChannelId(consumerTag);
                            subscribeReturn.setRid("");
                            subscribeReturn.setOk(true);
                            subscribeReturn.setConsumerTag(consumerTag);
                            subscribeReturn.setBasicProperties(basicProperties);
                            subscribeReturn.setBody(body);
                            byte[] payload = BinaryTool.toBytes(subscribeReturn);
                            // 将响应返回给客服端
                            Response response = new Response();
                            response.setType(0xc);
                            response.setLength(payload.length);
                            response.setPayload(payload);
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream, response);
                        }
                    });
        } else if (request.getType() == 0xb) {
            // 调用ack确认消息
            BasicAckArgument argument = (BasicAckArgument) BinaryTool.fromBytes(request.getPayload());
            ok = virtualHost.basicAck(argument.getQueueName(), argument.getMessageId());
        } else {
            throw new MqException("[BrokerServer] 操作失败！未知type = " + request.getType());
        }
        // 构造响应并返回
        BasicReturn basicReturn = new BasicReturn();
        basicReturn.setChannelId(basicArgument.getChannelId());
        basicReturn.setRid(basicArgument.getRid());
        basicReturn.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturn);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[BrokerServer] 返回响应：type = " + request.getType() + ",length = " + response.getLength()
                + ",channelId = " + basicArgument.getChannelId() + ",rid = " + basicArgument.getRid());
        return response;
    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        // 写入客户端的响应格式
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        dataOutputStream.flush();
    }

    // 清理关闭了的socket连接
    private void clearClosedSession(Socket clientSocket) {
        // 由于不能一边遍历一边删除，所以需要将channelId记录下来
        List<String> toDeleteChannelId = new LinkedList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == clientSocket) {
                toDeleteChannelId.add(entry.getKey());
            }
        }
        // 记录channelId之后在删除
        for (String channelId : toDeleteChannelId) {
            sessions.remove(channelId);
            System.out.println("[BrokerServer] 清理关闭的socket连接，channelId = " + toDeleteChannelId);
        }
    }
}
